<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use fast\Random;
use phpCAS;
use think\Session;
use think\helper\Time;
use app\admin\model\Outsideschool as outside;
use think\Config;
use think\Db;
use app\admin\model\ReceptionUnit;
use think\Validate;

class Outsideschool1 extends Frontend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $layout = 'weiui';
    protected $model = null;


    public function _initialize(){

        parent::_initialize();
        if (!Session::get('uid')){
//            require_once ROOT_PATH.'\public\cas\index1.php';
        }
        $this->model = new outside();
        $action = strtolower(request()->action());

        //调试使用
        if (input('admin') == 'super'){
            $_SESSION['uid'] = '200501067';
            $_SESSION['cn'] = '马伟萍';
        }
        if(!empty($_GET['type'])&&$_GET['type']==1)
        {
            $_SESSION['uid'] = '198601025';
            $_SESSION['cn'] = '张文军';
        }
       // $_SESSION['uid'] = '199401025';
       // $_SESSION['cn'] = '肖传强';

        if (in_array($action, ['index','view', 'ajax','log', 'info'])){
            if(empty($_COOKIE['keeplogin'])){
                if (!isset($_SESSION['uid']) || $_SESSION['uid'] == ""){
                    $this->redirect(request()->domain() . '/cas/index.php');
                    exit;
                }
                session('uid', $_SESSION['uid']);
                session('cn', $_SESSION['cn']);
            }
            $_COOKIE['keeplogin'] = 86400 * 7 +time();
        }
        
        halt($_COOKIE);
        
    }

    public function index($ids = 1){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            //黑名单
            //$re = $this->blacklist($params['tel'],$params['card_id']);
            $re = $this->blacklist($params['nickname']);
            if (!$re){
                $this->error('你好，此用户不允许登录');
            }
            $params['create_time'] = time();
            $params['applier_id'] = session('uid')?:'';//申请人id
            $params['applier_name'] = session('cn')?:'';//申请人名称
            $info = ReceptionUnit::get($params['reception_id']);
            $params['reception_name'] = $info['name'];
            if ($params['admission_starttime'])
                $params['admission_starttime'] = str_replace('/', '', $params['admission_starttime']);
            if ($params['admission_endtime'])
                $params['admission_endtime'] = str_replace('/', '', $params['admission_endtime']);
            if ($params['admission_endtime'] < $params['admission_starttime'])
                $this->error('入校截止时间不能小于入校开始时间');
            $res = $this->model->allowField(true)->save($params);
            if ($res){
                if($info -> sid){
                    // $msg = urlencode(mb_convert_encoding("您有一份{$params['applier_name']}老师提交的校外人员入校预约申请需要审批。",'gb2312'));
                    // $url = 'http://114.255.71.158:8061/?username=qdnydx&password=QAUnmc123&message='.$msg.'&phone='.($info -> mobile).'&epid=122985&linkid=&subcode=';
                    // geturl($url);//发送短信
                    $sid_arr = explode(',',$info->sid);
                    foreach($sid_arr as $key => $v){
                        send_wechat_work_msg([$v], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$params['applier_name'].'提交的入校预约申请需要审批。</a>');
                    }
                    // send_wechat_work_msg([201401047], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$params['applier_name'].'提交的入校预约申请需要审批。</a>');
                }
                $this->success('登记成功', '', ['nickname' => $params['nickname']]);
            }
            else{
                $this->error('登记失败');
            }
        }
        //接待单位
        $where = [];
        //测试用部门
        if (!input('admin_test')){
            $where['id'] = ['<>',1];
        }
        $reception_unit = ReceptionUnit::where($where)->where('sort>0')->order('sort')->field("name,id")->select();
        $this->assign('reception_unit', $reception_unit);

        $this->assign('ids', $ids);
        $title = '入校登记';
        $this->assign('pageTitle', $title);

        $teacherid=0;
        $teacher = Db::name('teacher')->where(['tel'=>$_SESSION['uid'],'nickname'=>$_SESSION['cn']])->find();
        if($teacher){
            $teacherid = $teacher['id'];
        }
        $this->assign('teacherid', $teacherid);

        
        return $this->fetch();
    }

    public function index2($ids = 1){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            //黑名单
            //$re = $this->blacklist($params['tel'],$params['card_id']);
            $re = $this->blacklist($params['nickname']);
            if (!$re){
                $this->error('你好，此用户不允许登录');
            }
            $params['create_time'] = time();
            $params['applier_id'] = session('uid')?:'';//申请人id
            $params['applier_name'] = session('cn')?:'';//申请人名称
            $info = ReceptionUnit::get($params['reception_id']);
            $params['reception_name'] = $info['name'];
            if ($params['admission_starttime'])
                $params['admission_starttime'] = str_replace('/', '', $params['admission_starttime']);
            if ($params['admission_endtime'])
                $params['admission_endtime'] = str_replace('/', '', $params['admission_endtime']);
            if ($params['admission_endtime'] < $params['admission_starttime'])
                $this->error('入校截止时间不能小于入校开始时间');
//            $res = $this->model->allowField(true)->save($params);
            // $msg = urlencode(mb_convert_encoding("您有一份{$params['applier_name']}老师提交的校外人员入校预约申请需要审批。",'gb2312'));
//            $url = 'http://114.255.71.158:8061/?username=qdnydx&password=QAUnmc123&message='.$msg.'&phone='.($info -> mobile).'&epid=122985&linkid=&subcode=';
            // $url = 'http://114.255.71.158:8061/?username=qdnydx&password=QAUnmc123&message='.$msg.'&phone=15954275057,18153227097&epid=122985&linkid=&subcode=';
            // geturl($url);

            // send_wechat_work_msg([15954275057], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$params['applier_name'].'提交的入校预约申请需要审批。</a>');

//            if ($res){
//                if($info -> mobile){
//                    $msg = urlencode(mb_convert_encoding("您有新的入校申请待审核，申请人{$params['applier_name']}，校外入校人{$params['nickname']}",'gb2312'));
//                    echo $url = 'http://114.255.71.158:8061/?username=qdnydx&password=QAUnmc123&message='.$msg.'&phone='.($info -> mobile).'&epid=122985&linkid=&subcode=';
//                }
//                $this->success('登记成功', '', ['nickname' => $params['nickname']]);
//            }
//            else{
//                $this->error('登记失败');
//            }
        }
        //接待单位
        $where = [];
        //测试用部门
        if (!input('admin_test')){
            $where['id'] = ['<>',1];
        }
        $reception_unit = ReceptionUnit::where($where)->where('sort>0')->order('sort')->field("name,id")->select();
        $this->assign('reception_unit', $reception_unit);

        $this->assign('ids', $ids);
        $title = '入校登记';
        $this->assign('pageTitle', $title);
        return $this->fetch('index');
    }

    /**
     * 查看列表
     */
    public function view(){

        if ($this->request->isPost()){
            $page = input('page', 1);
            $page_size = input('size', 10);
            $is_check = trim(input('is_check', ''));
            $keyword = trim(input('keyword', ''));

            $where = array();
//            $where['is_check'] = 0;

            // 判断是否登录,登录后返回session
            $sid = Session::get('uid');
            $nickname = Session::get('cn');
            // 获取当前负责人所在的接待单位id
//            $reception_info = ReceptionUnit::where(['sid' => $sid, 'nickname' => $nickname])->field("name,id")->find();
            if($sid=='200101024'){ //车广杰有多个学校审核权限
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->column('id');
            }else{
                //其他
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->find();
            }
            
            if (!empty($reception_info)){
                if($sid=='200101024'){
                    $where['reception_id'] = ['in',$reception_info];
                }else{
                    $where['reception_id'] = $reception_info['id'];
                }
            } else{
                $where['reception_id'] = '--';
            }
            if (strlen($is_check) > 0){
                $where['is_check'] = $is_check;
            }
            if ($is_check == 0){
//                $where['admission_starttime'] = ['<=',date('Ymd')];
                $where['admission_endtime'] = ['>=',date('Ymd')];
            }
            if (strlen($keyword) > 0){
                $where['tel'] = ['like', '%' . $keyword . '%'];
            }

            $outside_list = $this->model->where($where)->order('id desc')->paginate($page_size)->toArray();
            foreach ($outside_list['data'] as $k => &$v){
//                $v['admission_time'] = date('Y-m-d', strtotime($v['admission_time']));
                $v['key'] = (($page - 1) * $page_size) + 1 + $k;
            }
            return $this->success('success', '', $outside_list);
//            $this->assign('outside_list', $outside_list);
        }
        $this->assign('check_option', outside::is_check);

//        $title = '校外人员入校申请审核';
        $title = '';
        $this->assign('pageTitle', $title);
        $this->assign('page_type', 'view');
        $this->assign('go_list', '<div class="apply-list"><a href="log">申请记录</a>');

        $teacherid=0;
        $teacher = Db::name('teacher')->where(['tel'=>$_SESSION['uid'],'nickname'=>$_SESSION['cn']])->find();
        if($teacher){
            $teacherid = $teacher['id'];
        }
        $this->assign('teacherid', $teacherid);


        return $this->fetch();
    }
    /**
     * 查看列表
     */
    public function log(){
        if(input('demo') && input('demono')){
            Session::set('demo',input('demo'));
            Session::set('demono',input('demono'));
        }
        if ($this->request->isPost()){
            $page = input('page', 1);
            $page_size = input('size', 10);
            $is_check = trim(input('is_check', ''));
            $keyword = trim(input('keyword', ''));

            $where = array();
//            $where['is_check'] = 0;

            // 判断是否登录,登录后返回session
            $sid = Session::get('uid');

            $where['applier_id'] = $sid;
            if(session('demo') && session('demono')){
                $where['applier_id'] = session('demono');
            }

            if (strlen($is_check) > 0){
                $where['is_check'] = $is_check;
            }
//            if ($is_check == 0){
////                $where['admission_starttime'] = ['<=',date('Ymd')];
//                $where['admission_endtime'] = ['>=',date('Ymd')];
//            }
            if (strlen($keyword) > 0){
                $where['tel'] = ['like', '%' . $keyword . '%'];
            }

            $outside_list = $this->model->where($where)->order('id desc')->paginate($page_size)->toArray();

            foreach ($outside_list['data'] as $k => &$v){
//                $v['admission_time'] = date('Y-m-d', strtotime($v['admission_time']));
                $v['key'] = (($page - 1) * $page_size) + 1 + $k;
            }
            return $this->success('success', '', $outside_list);
//            $this->assign('outside_list', $outside_list);
        }
        $this->assign('check_option', outside::is_check);

        $title = '';
//        $title = '校外人员入校申请记录';
        $this->assign('pageTitle', $title);
        $this->assign('page_type', 'log');
        $this->assign('go_list', '<div class="apply-list"><a href="view">申请审核</a>');

        $teacherid=0;
        $teacher = Db::name('teacher')->where(['tel'=>$_SESSION['uid'],'nickname'=>$_SESSION['cn']])->find();
        if($teacher){
            $teacherid = $teacher['id'];
        }
        $this->assign('teacherid', $teacherid);

        return $this->fetch('view');
    }


    /**
     * 查看详情
     */
    public function info($id = ''){
        $ids = input('id');
        if (!$ids)
            $this->error('该记录不存在');
        // var_dump('233');
        // halt(Db::table('qa_outsideschool')->page(1,10)->select());
        // $outside_info = $this->model->where(['id' => $ids])->find();
        $outside_info = $this->model->where('id',$ids)->find();
        
        $outside_info['card1'] = substr($outside_info['card_id'],0,17);
        $outside_info['card2']= substr($outside_info['card_id'],-1);
        unset($outside_info['card_id']);

        // halt($outside_info);
        // halt('%7B%22id%22%3A50651%2C%22applier_id%22%3A%22200101048%22%2C%22applier_name%22%3A%22%5Cu738b%5Cu9053%5Cu541b%22%2C%22nickname%22%3A%22%5Cu5218%5Cu8d85%22%2C%22card_id%22%3A%22370306199609113910%22%2C%22tel%22%3A%2217864276509%22%2C%22work_unit%22%3A%22%5Cu534e%5Cu516e%5Cu4f53%5Cu80b2%22%2C%22memo%22%3A%22%5Cu4e1c%5Cu8db3%5Cu7403%5Cu573a%5Cu7ef4%5Cu4fee%22%2C%22create_time%22%3A1654566426%2C%22update_time%22%3A1654566426%2C%22admission_starttime%22%3A20220607%2C%22admission_endtime%22%3A20220608%2C%22healthy_pic%22%3A%22%5C%2Fuploads%5C%2F20220607%5C%2Fee6e38be864aa029f1a9a3ac23751b7e.png%22%2C%22trip_pic%22%3A%22%5C%2Fuploads%5C%2F20220607%5C%2F8824b9a21eb8e13be043539e54ce681b.png%22%2C%22nuclein_pic%22%3A%22%5C%2Fuploads%5C%2F20220607%5C%2F0e32644f469003c1a4cec1aa8ef800a4.png%22%2C%22reception_id%22%3A54%2C%22reception_name%22%3A%22%5Cu4f53%5Cu80b2%5Cu6559%5Cu5b66%5Cu90e8%22%2C%22is_check%22%3A0%2C%22check_time%22%3Anull%2C%22check_sid%22%3Anull%2C%22check_cn%22%3A%22%22%2C%22is_use%22%3A0%2C%22use_time%22%3Anull%2C%22use_time_record%22%3Anull%2C%22gate_name%22%3A%22%22%2C%22gate_id%22%3Anull%2C%22is_been_highrisk%22%3A0%2C%22is_uncomfortable%22%3A0%2C%22car_number%22%3A%22%22%7D');
        // halt(urlencode(json_encode($outside_info)));
        // $outside_info = base64_encode(json_encode($outside_info));
        // var_dump($outside_info);
        // halt($outside_info);
        $this->assign('outside_info', $outside_info);

        $title = '';
//        $title = '校外人员入校登记详情';
        $this->assign('pageTitle', $title);
        $this->assign('from', input('from'));
        return $this->fetch();
    }

    /**
     * 审核
     */
    public function ajax($id = ''){
        if ($this->request->isPost()){

            $sid = Session::get('uid');
            if($sid=='200101024'){
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->column('id');
            }else{
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->find();
            }
            if (!$reception_info){
                $this->error('您无审核权限');
            }

            $params = $this->request->post("row/a");
            //表单验证
            if (!isset($params['id']) || $params['id'] <= 0){
                $this->error('数据异常，审核失败','',$params);
            }
            if (!isset($params['check']) || !in_array($params['check'], [1, 2])){
                $this->error('数据异常，审核失败','',$params);
            }

            if ($params['id'])

                $info = \app\admin\model\Outsideschool::get($params['id']);
                if (!$info){
                    $this->error('数据异常，审核失败','',$params);
                }
                if($sid!='200101024'){
                    if ($info['reception_id'] != $reception_info['id']){
                        $this->error('您无审核权限');
                    }
                }
//                $update['is_check'] = 1;
                $update['check_sid'] = session('uid');
                $update['check_cn'] = session('cn');
                $update['is_check'] = $params['check'];
                $update['check_time'] = time();
            $res = Db::name('outsideschool')->where(['id' => $params['id']])->update($update);

            if ($res)
                if ($params['check'] == 1){
                    $this->success('审核成功', '');
                } else{
                    $this->success('申请已驳回', '');
                }
            else{
                if ($params['check'] == 1){
                    $this->error('审核失败');
                } else{
                    $this->error('驳回失败');
                }
            }
        }
    }
    /*
     * 退出登录
     */
    public function loginout(){
        $_SESSION['uid'] = null;
        $_SESSION['cn'] = null;
        session('uid',null);
        session('cn',null);
//        $this->curlpost(request()->domain() . '/cas/index.php?logout=1');
//        file_get_contents(request()->domain() . '/cas/index.php?logout=1');
//        $this->redirect(url('view'));
        $this->redirect(request()->domain() . '/cas/index.php?logout=1');
        exit;
    }

    /*
     * 黑名单
     */
//    public function blacklist($mobile,$card){
//        $user_arr = [
//            ['mobile' => 18661473759, 'card' => 622428199102141418],
//        ];
//        foreach ($user_arr as $k => $v)
//        {
//            if($v['mobile']==$mobile && $v['card']==$card)
//            {
//                return false;
//            }
//        }
//        return true;
//    }

    public function blacklist($nickname){
        $user = [
            ['nickname' => '袁绍东'],
        ];
        foreach ($user as $k => $v)
        {
            if($v['nickname']==$nickname)
            {
                return false;
            }
        }
        return true;
    }

}